package tr.edu.metu.is550.isell.utils;

import android.content.Context;
import android.util.Base64;
import tr.edu.metu.is550.isell.R;

import javax.crypto.Cipher;
import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;

public class CryptoUtils {
    public static String encryptAndBase64Encode(Context ctx, String s) {

        String result = "";
        InputStream inputStream = null;
        try {
            System.out.println("**** " + s);
            inputStream = ctx.getResources().openRawResource(R.raw.publickey);
            KeyStore publicKeyStore = KeyStore.getInstance("BKS");
            publicKeyStore.load(inputStream, "isellpass".toCharArray());
            Certificate certificate = publicKeyStore.getCertificate("isell");
            Key isell = certificate.getPublicKey();
            System.out.println(isell.getFormat() + " " + isell.getAlgorithm());
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, isell);
            byte[] bytes = cipher.doFinal(s.getBytes());
            result = new String(Base64.encode(bytes, Base64.NO_WRAP), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
        return result;
    }
}
